package com.gome.ai.aiparter.ws;

import com.alibaba.fastjson.JSON;
import com.gome.ai.aiparter.ws.em.ActionEnum;
import com.gome.ai.aiparter.ws.enity.WSRequest;
import com.gome.ai.aiparter.ws.enity.WSResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class UserConnection implements WSConnection {
    protected final WebSocketServer server;

    public UserConnection(WebSocketServer server) {
        this.server = server;
    }

    @Override
    public void onMessage(String message) {
        WSRequest request = JSON.parseObject(message, WSRequest.class);
        if (request.getAct() == ActionEnum.ASK.getCode()) {
            onAsk(request,message);
        }else {
            log.warn("用户未知消息:{}",message);
        }
    }

    protected void onAsk(WSRequest request,String message){
        AIConnection aiClient = null;
        try {
            aiClient = AIConnection.idleAIs.poll(1, TimeUnit.SECONDS);
            log.debug("空闲AI数量 size = {}",AIConnection.idleAIs.size());
        } catch (InterruptedException e) {
            log.warn("");
        }

        if(aiClient != null){
            log.info("获取到AI载荷");

            //转发AI返回的消息
            aiClient.answer(server::send);
            aiClient.ask(message);
        }else {
            log.warn("AI全忙");
            WSResponse response = new WSResponse();
            response.setAct(ActionEnum.ALL_AI_BUSY.getCode());
            response.setMsg(ActionEnum.ALL_AI_BUSY.getName());
            server.send(JSON.toJSONString(response));
        }
    }
}
